package com.atguigu.tingshu.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.NestedQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.TermsQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.TermsQueryField;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggest;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import co.elastic.clients.elasticsearch.xpack.usage.Base;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.lettuce.core.GeoArgs;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Request;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private AlbumIndexRepository albumIndexRepository;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private SuggestIndexRepository suggestIndexRepository;

    @Autowired
    private RedisTemplate redisTemplate;



    //专辑上架接口


//    @Override
    public void upperAlbum1(Long albumId) {
        //远程调用获取上架专辑需要的所有数据 添加到es里面
        //1  远程调用获取数据 封装到albumInfoIndex
        //根据专辑id获取专辑基本信息
        Result<AlbumInfo> albumInfoR = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfo = albumInfoR.getData();
        Assert.notNull(albumInfo,"专辑数据为空");
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        BeanUtils.copyProperties(albumInfo,albumInfoIndex);
        // 2 根据用户id获取用户信息
        Long userId = albumInfo.getUserId();
        Result<UserInfoVo> userInfoVoR = userInfoFeignClient.getUserInfoVo(userId);
        UserInfoVo userInfoVo = userInfoVoR.getData();
        Assert.notNull(userInfoVo,"用户数据为空");
        //3 根据三级分类id 获取一级和二级
        Long category3Id = albumInfo.getCategory3Id();
        Result<BaseCategoryView> categoryViewR = categoryFeignClient.getCategoryView(category3Id);
        BaseCategoryView categoryView = categoryViewR.getData();
        Assert.notNull(categoryView,"分类数据为空");

        //4 根据专辑id获取四个统计数据
        Result albumStatR = albumInfoFeignClient.getAlbumStat(albumId);
        Map<String,Object> map = (Map<String, Object>) albumStatR.getData();
        //获取map中的PlayStatNum
        Integer playStatNum = (Integer) map.get("playStatNum");
        Integer subscribeStatNum = (Integer) map.get("subscribeStatNum");
        Integer buyStatNum = (Integer) map.get("buyStatNum");
        Integer commentStatNum = (Integer) map.get("commentStatNum");

        //5 根据专辑id获取属性信息
        Result<List<AlbumAttributeValue>> albumAttributeValueR = albumInfoFeignClient.findAlbumAttributeValue(albumId);
        List<AlbumAttributeValue> albumAttributeValueList = albumAttributeValueR.getData();

        //赋值属性信息
        if(!CollectionUtils.isEmpty(albumAttributeValueList)){
            List<AttributeValueIndex> attributeValueIndexList = albumAttributeValueList.stream().map(albumAttributeValue -> {
                AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                return attributeValueIndex;
            }).collect(Collectors.toList());
            //保存数据
            albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
        }
        //赋值分类数据

        albumInfoIndex.setCategory1Id( categoryView.getCategory1Id());
        albumInfoIndex.setCategory2Id(categoryView.getCategory2Id());
        albumInfoIndex.setCategory3Id(categoryView.getCategory3Id());

        //赋值用户名称
        albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());

        //赋值四个统计数据
        albumInfoIndex.setPlayStatNum(playStatNum);
        albumInfoIndex.setPlayStatNum(subscribeStatNum);
        albumInfoIndex.setPlayStatNum(buyStatNum);
        albumInfoIndex.setPlayStatNum(commentStatNum);
        double hotScore = playStatNum*0.2 + subscribeStatNum*0.3 + buyStatNum*0.4 + commentStatNum*0.1;
        //  设置热度排名
        albumInfoIndex.setHotScore(hotScore);
        //调用方法添加到es
        albumIndexRepository.save(albumInfoIndex);
    }

    //专辑上架接口 优化版本
    @Override
    public void upperAlbum(Long albumId) {
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        //使用并发多线程进行优化
        //根据专辑id获取专辑基本信息
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            AlbumInfo albumInfo = albumInfoResult.getData();
            //封装到albumInfoIndex中去
            BeanUtils.copyProperties(albumInfo,albumInfoIndex);
            return albumInfo;
        });
        // 2 根据用户id获取用户信息

        CompletableFuture<Void> UserInfoVoCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync((albumInfo) -> {
            Long userId = albumInfo.getUserId();
            Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
            UserInfoVo userInfoVo = userInfoVoResult.getData();
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
        });
        //3 根据三级分类id 获取一级和二级
        CompletableFuture<Void> BaseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync((albumInfo) -> {
            Long category3Id = albumInfo.getCategory3Id();
            Result<BaseCategoryView> categoryViewResult = categoryFeignClient.getCategoryView(category3Id);
            BaseCategoryView categoryView = categoryViewResult.getData();
            albumInfoIndex.setCategory1Id(categoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(categoryView.getCategory2Id());
            albumInfoIndex.setCategory3Id(categoryView.getCategory3Id());
        });
        //4 根据专辑id获取四个统计数据
        CompletableFuture<Void> MapCompletableFuture = CompletableFuture.runAsync(() -> {
            Result albumStatResult = albumInfoFeignClient.getAlbumStat(albumId);
            Map<String, Object> map = (Map<String, Object>) albumStatResult.getData();
            Integer playStatNum = (Integer) map.get("playStatNum");
            albumInfoIndex.setPlayStatNum(playStatNum);
            Integer subscribeStatNum = (Integer) map.get("subscribeStatNum");
            Integer buyStatNum = (Integer) map.get("buyStatNum");
            Integer commentStatNum = (Integer) map.get("commentStatNum");
            albumInfoIndex.setPlayStatNum(subscribeStatNum);
            albumInfoIndex.setPlayStatNum(buyStatNum);
            albumInfoIndex.setPlayStatNum(commentStatNum);
        });
        //5 根据专辑id获取属性信息
        CompletableFuture<Void> AlbumAttributeValueCompletableFuture = CompletableFuture.runAsync(() -> {
            Result<List<AlbumAttributeValue>> albumAttributeValueResult = albumInfoFeignClient.findAlbumAttributeValue(albumId);
            List<AlbumAttributeValue> albumAttributeValues = albumAttributeValueResult.getData();
            List<AttributeValueIndex> attributeValueIndices = albumAttributeValues.stream().map(
                    albumAttributeValue -> {
                        AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                        BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                        return attributeValueIndex;
                    }
            ).collect(Collectors.toList());

        });
        //等待所有线程完成，再合并
        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                UserInfoVoCompletableFuture,
                BaseCategoryViewCompletableFuture,
                MapCompletableFuture,
                AlbumAttributeValueCompletableFuture
        ).join();
        //添加到es中
        albumIndexRepository.save(albumInfoIndex);

        //进行自动补全的数据初始化

        SuggestIndex suggestIndex = new SuggestIndex();
        suggestIndex.setId(UUID.randomUUID().toString().replaceAll("-"," "));
        suggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
        suggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle())}));
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle())}));
        suggestIndexRepository.save(suggestIndex);

    }

    //专辑下架
    @Override
    public void lowerAlbum(Long albumId) {
        albumIndexRepository.deleteById(albumId);
    }

    //根据关键词进行搜索
    @Override
    public AlbumSearchResponseVo searchBykey(AlbumIndexQuery albumIndexQuery) {
        //AlbumSearchResponseVo封装的数据是用户可能输入的条件
        //构建dsl语句
        SearchRequest request =  this.buildQueryDSL(albumIndexQuery);
        try {
            SearchResponse<AlbumInfoIndex> response = elasticsearchClient.search(request, AlbumInfoIndex.class);
            //把es查询出来的最终结果封装成albumSearchResponseVo对象(检索的结果)
            AlbumSearchResponseVo albumSearchResponseVo = this.praseSearchResult(response);
            //当前页
            albumSearchResponseVo.setPageNo(albumIndexQuery.getPageNo());
            //每页记录数
            albumSearchResponseVo.setPageSize(albumIndexQuery.getPageSize());

            //获取总页数  = 总条数/每页记录数
//            long total = albumSearchResponseVo.getTotal();
//            Integer pageSize = albumIndexQuery.getPageSize();
//            Long totalPages =null;
//            if(total % pageSize==0){
//               totalPages = total/pageSize;
//            }else{
//               totalPages = total/pageSize +1;
//            }
//            albumSearchResponseVo.setTotalPages(totalPages);
// 获取总页数  (总记录数 + 每页显示记录 -1) / 每页显示记录数
            long totalPages =
                    (albumSearchResponseVo.getTotal() + albumIndexQuery.getPageSize() - 1) / albumIndexQuery.getPageSize();
            return albumSearchResponseVo;
        } catch (IOException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    //把最终结果封装成AlbumSearchResponseVo对象
    private AlbumSearchResponseVo praseSearchResult(SearchResponse<AlbumInfoIndex> response) {


        AlbumSearchResponseVo albumSearchResponseVo = new AlbumSearchResponseVo();
        long total = response.hits().total().value();
        albumSearchResponseVo.setTotal(total);

        List<Hit<AlbumInfoIndex>> hitList = response.hits().hits();
        if(!CollectionUtils.isEmpty(hitList)){
            List<AlbumInfoIndexVo> albumInfoIndexVoList = hitList.stream().map(hit -> {
                AlbumInfoIndex albumInfoIndex = hit.source();
                AlbumInfoIndexVo albumInfoIndexVo = new AlbumInfoIndexVo();
                BeanUtils.copyProperties(albumInfoIndex, albumInfoIndexVo);
                //判断用户是否根据关键词搜索
                if (null != hit.highlight().get("albumTitle")) {
                    //获取高亮数据
                    String albumTitle = hit.highlight().get("albumTitle").get(0);
                    albumInfoIndexVo.setAlbumTitle(albumTitle);
                }
                return albumInfoIndexVo;
            }).collect(Collectors.toList());
            albumSearchResponseVo.setList(albumInfoIndexVoList);
        }
        return albumSearchResponseVo;
    }
    //构建DSL语句
    private SearchRequest buildQueryDSL(AlbumIndexQuery albumIndexQuery) {
        //创建requestBuilder对象
        SearchRequest.Builder requestBuilder = new SearchRequest.Builder();

        BoolQuery.Builder boolQuery = new BoolQuery.Builder();
        /*
            POST /my_index/_search
            {
              "query": {
                "bool":{
         */

        if(StringUtils.hasText(albumIndexQuery.getKeyword())){
            boolQuery.should(s->s.match(m->m.field("albumTitle").query(albumIndexQuery.getKeyword())))
                    .should(s->s.match(m->m.field("albumIntro").query(albumIndexQuery.getKeyword())));
            //高亮显示  和query同一个级别
            requestBuilder.highlight(h->h.fields("albumTitle"
                    ,f->f.preTags("<span style=color:red>").postTags("</span>")));
        }
        Long category1Id = albumIndexQuery.getCategory1Id();
        if(category1Id!=null){
            boolQuery.filter(f->f.term(t->t.field("category1Id").value(category1Id)));
        }
        Long category2Id = albumIndexQuery.getCategory2Id();
        if(category2Id!=null){
            boolQuery.filter(f->f.term(t->t.field("category2Id").value(category2Id)));
        }
        if(albumIndexQuery.getCategory3Id()!=null){
            boolQuery.filter(f->f.term(t->t.field("category3Id").value(albumIndexQuery.getCategory3Id())));
        }
        //  分页  from和size跟query是同一个级别
        //当前页
        Integer pageNo = albumIndexQuery.getPageNo();
        //每页大小
        Integer pageSize = albumIndexQuery.getPageSize();
        Integer current = (pageNo-1)*pageSize;
        //当前位置
        requestBuilder.from(current);
        requestBuilder.size(pageSize);

        //排序
        //排序字段根据前端传递的字段和排序方式进行处理
        //1 : desc
        //定义一个排序字段
        String orderField="";
        //定义排序方式
        String sort = "";
        String order = albumIndexQuery.getOrder();
        if(StringUtils.hasText(order)){
            String[] split = order.split(":");
            if(split!=null && split.length==2){
                switch (split[0]){
                    case "1":
                        orderField = "hotScore";
                        break;
                    case "2":
                        orderField = "playStatNum";
                        break;
                    case "3":
                        orderField="createTime";
                        break;
                }
                sort = split[1];
            }
//        requestBuilder.sort(s->s.field(p->p.field("playStatNum").order(SortOrder.Desc)));
            String finalOrderField = orderField;
            String finalSort = sort;
            requestBuilder.sort(s->s.field(p->p.field(finalOrderField).order("desc".equals(finalSort)? SortOrder.Desc : SortOrder.Asc)));
        }else{
            //如果order为空，就添加一个默认的排序方式
            requestBuilder.sort(s->s.field(p->p.field("_score").order(SortOrder.Desc)));
        }
        //属性id : 属性值id
        List<String> attributeList = albumIndexQuery.getAttributeList();
       if(!CollectionUtils.isEmpty(attributeList)){
           attributeList.forEach((attribute)->{
               //按照：进行分割
               String[] split = attribute.split(":");
               if(split!=null && split.length==2){
                   //  创建nestedQuery 对象
                 NestedQuery nestedQuery = NestedQuery.of(
                         n->n.path("attributeValueIndexList")
                                 .query(q->q.bool(b->b.must(m->m.term(
                                         t->t.field("attributeValueIndexList.attributeId").value(split[0])))
                                         .must(m->m.term(t->t.field("attributeValueIndexList.valueId").value(split[1]))))));
                  boolQuery.filter(f->f.nested(nestedQuery));
               }
           });
       }
        requestBuilder.index("albuminfo").query(q -> q.bool(boolQuery.build()));
        SearchRequest request = requestBuilder.build();
        return request;
    }


    //获取频道页数据
    @Override
    public List<Map<String, Object>> channel(Long category1Id) {
         //1 远程调用  根据一级分类id获取下面前七个三级分类的数据
        Result<List<BaseCategory3>> category3IdByCategory1Id = categoryFeignClient.getCategory3IdByCategory1Id(category1Id);
        //2  从查询的所有三级分类数据里面获取所有的三级分类id集合
        List<BaseCategory3> baseCategory3List = category3IdByCategory1Id.getData();
        //把baseCategory3List转换成map
        Map<Long, BaseCategory3>  category3Map = baseCategory3List.stream().collect(Collectors.toMap(BaseCategory3::getId, BaseCategory3 -> BaseCategory3));
        List<Long> idList = baseCategory3List.stream().map(baseCategory3 -> {
            Long baseCategory3Id = baseCategory3.getId();
            return baseCategory3Id;
        }).collect(Collectors.toList());
        //List<long> -- List<FieldValue>
        List<FieldValue> valueList = idList.stream().map(id -> FieldValue.of(id)).collect(Collectors.toList());


        //3 构建DSL语句  查询es得到专辑数据
        // 根据三级分类id集合进行查询  根据三级分类id进行分组 每组获取热门前6个专辑
        SearchRequest.Builder request = new SearchRequest.Builder();
        request.index("albuminfo").query(q->q.terms(
                t->t.field("category3Id").terms(new TermsQueryField.Builder().value(valueList).build())));
        request.aggregations("groupByCategory3IdAgg",a->a.terms(t->t.field("category3Id").size(10))
                        .aggregations("topTenHotScoreAgg",i->i.topHits(t->t.size(6)
                                .sort(s->s.field(f->f.field("hotScore").order(SortOrder.Desc))))));
//        SearchRequest build = request.build();
//        System.out.println(build.toString());

        try {

            SearchResponse<AlbumInfoIndex> response = elasticsearchClient.search(request.build(), AlbumInfoIndex.class);
            //  声明集合
            List<Map<String, Object>> result = new ArrayList<>();
            Aggregate groupByCategory3IdAgg = response.aggregations().get("groupByCategory3IdAgg");
            groupByCategory3IdAgg.lterms().buckets().array().forEach(item->{
                //创建集合
                ArrayList<AlbumInfoIndex> albumInfoIndexArrayList = new ArrayList<>();
                //三级分类的id
                long category3Id = item.key();
                Aggregate topTenHotScoreAgg = item.aggregations().get("topTenHotScoreAgg");
                List<Hit<JsonData>> hits = topTenHotScoreAgg.topHits().hits().hits();
                hits.forEach(hit->{
                    String json = hit.source().toString();
                    AlbumInfoIndex albumInfoIndex = JSON.parseObject(json, AlbumInfoIndex.class);
                    albumInfoIndexArrayList.add(albumInfoIndex);
                });
                //  声明一个map 集合数据
                Map<String, Object> map = new HashMap<>();
                map.put("baseCategory3",category3Map.get(category3Id));
                map.put("list",albumInfoIndexArrayList);
                result.add(map);
            });
            //4 得到结果 按照要求进行封装 最终返回
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }

    //实现自动补全功能
    @Override
    public List<String> completeSuggest(String keyword) {
        SearchRequest.Builder request = new SearchRequest.Builder();

        request.index("suggestinfo").suggest(s->s.suggesters("suggestionKeyword"
                ,s1->s1.prefix(keyword).completion(c->c.field("keyword")
                        .skipDuplicates(true).size(10).fuzzy(f->f.fuzziness("auto"))))
                .suggesters("suggestionkeywordPinyin",s2->s2.prefix(keyword)
                        .completion(c->c.field("keywordPinyin").skipDuplicates(true)
                                .size(10).fuzzy(f->f.fuzziness("auto"))))
                .suggesters("suggestionkeywordSequence",a->a.prefix(keyword)
                        .completion(c->c.field("keywordSequence").skipDuplicates(true)
                                .size(10).fuzzy(f->f.fuzziness("auto"))))
        );

        try {
            SearchResponse<SuggestIndex> response = elasticsearchClient.search(request.build(), SuggestIndex.class);
            HashSet<String> titleSet = new HashSet<>();
            titleSet.addAll(this.parseSearchResult(response,"suggestionKeyword"));
            titleSet.addAll(this.parseSearchResult(response,"suggestionkeywordPinyin"));
            titleSet.addAll(this.parseSearchResult(response,"suggestionkeywordSequence"));
            return new ArrayList<>(titleSet);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


    /**
     * 处理聚合结果集
     * @param response
     * @param suggestName
     * @return
     */
    private List<String> parseSearchResult(SearchResponse<SuggestIndex> response, String suggestName) {
        //  创建集合
        List<String> suggestList = new ArrayList<>();
        Map<String, List<Suggestion<SuggestIndex>>> groupBySuggestionListAggMap = response.suggest();
        groupBySuggestionListAggMap.get(suggestName).forEach(item -> {
            CompletionSuggest<SuggestIndex> completionSuggest =  item.completion();
            completionSuggest.options().forEach(it -> {
                SuggestIndex suggestIndex = it.source();
                suggestList.add(suggestIndex.getTitle());
            });
        });
        //  返回集合列表
        return suggestList;
    }

    //更新排行榜
    @Override
    public void updateLatelyAlbumRanking() {
        //1 远程调用  查询所有一级分类 得到list集合
     Result<List<BaseCategory1>> baseCategory1Result =  categoryFeignClient.getCategory1();
        List<BaseCategory1> baseCategory1List = baseCategory1Result.getData();

        //2 遍历所有一级分类集合 得到每个一级分类
        baseCategory1List.forEach(baseCategory1 -> {
            Long category1Id = baseCategory1.getId();
            String[] strings = new String[]{"hotScore",
                    "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"};
            for (String string : strings) {
                //3 拿着每个一级分类id+统计指标(播放量、评论量) 查询es
                //得到排序之后的数据
                SearchRequest.Builder request = new SearchRequest.Builder();
                request.index("albuminfo").query(q->q.term(t->t.field("category1Id").value(category1Id)
                )).sort(s->s.field(f->f.field(string).order(SortOrder.Desc)))
                        .size(10);
                try {
                    SearchResponse<AlbumInfoIndex> response = elasticsearchClient.search(request.build(), AlbumInfoIndex.class);
                    List<AlbumInfoIndex> albumInfoIndexList = response.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
                    //4 把每个一级分类里面根据不同指标排序之后的数据放到redis里
                    //使用redis的hash类型存储数据
                    //redis的key是一级分类id   field 是不同的指标  value是对应的数据
                    String rangkey = RedisConstant.RANKING_KEY_PREFIX+baseCategory1.getId();
                    redisTemplate.opsForHash().put(rangkey,string,albumInfoIndexList);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });


    }

    //获取排行榜列表
    @Override
    public List<AlbumInfoIndexVo> findRankingList(Long category1Id, String dimension) {
        String rangKey = RedisConstant.RANKING_KEY_PREFIX+category1Id;
        List<AlbumInfoIndexVo> albumInfoIndexVoList = (List<AlbumInfoIndexVo>)redisTemplate.opsForHash().get(rangKey, dimension);
        return albumInfoIndexVoList;
    }

}
